import type { FileNode } from './types';

// 为浏览器环境定义FileSystem API的类型
export interface FileSystemHandle {
  kind: 'file' | 'directory';
  name: string;
}

export interface FileSystemDirectoryHandle extends FileSystemHandle {
  entries: () => AsyncIterableIterator<[string, FileSystemHandle]>;
  getFileHandle: (name: string) => Promise<FileSystemFileHandle>;
  getDirectoryHandle: (name: string) => Promise<FileSystemDirectoryHandle>;
}

export interface FileSystemFileHandle extends FileSystemHandle {
  getFile: () => Promise<File>;
}

// 扩展Window接口以包含showDirectoryPicker方法
declare global {
  interface Window {
    showDirectoryPicker: (options?: {
      mode?: 'read' | 'readwrite';
    }) => Promise<FileSystemDirectoryHandle>;
  }
}

// 文件系统工具类
export class FileSystemUtils {
  // 选择文件夹并构建文件树
  static async selectFolderAndBuildTree(): Promise<{fileTree: FileNode[], rootHandle: FileSystemDirectoryHandle | null, folderPath: string, displayPath: string}> {
    try {
      // 请求用户选择文件夹
      const handle = await window.showDirectoryPicker({
        mode: 'read'
      });
      
      // 构建文件树
      const fileTree = await this.buildFileTree(handle, '', '');
      // 使用文件夹名称作为路径标识
      const folderPath = handle.name;
      
      // 由于浏览器安全限制，无法获取真实完整路径
      // 但我们可以尝试获取更多信息来构建更有意义的显示路径
      let displayPath = handle.name;
      
      // 尝试获取相对路径信息（在支持的浏览器中可能可用）
      try {
        // 注意：这只是一个尝试，浏览器可能不支持这种方式获取路径
        if (typeof handle === 'object' && handle.name) {
          // 为了提供更好的用户体验，我们显示文件夹名称作为路径
          displayPath = handle.name;
        }
      } catch (e) {
        // 忽略任何错误，继续使用文件夹名称
        console.log('无法获取更详细的路径信息:', e);
      }
      
      return { fileTree, rootHandle: handle, folderPath, displayPath };
    } catch (error) {
      console.error('选择文件夹出错:', error);
      return { fileTree: [], rootHandle: null, folderPath: '', displayPath: '' };
    }
  }

  // 构建文件树结构
  private static async buildFileTree(
    handle: FileSystemHandle,
    parentPath: string,
    rootId: string
  ): Promise<FileNode[]> {
    const fileTree: FileNode[] = [];
    
    if (handle.kind === 'directory') {
      const dirHandle = handle as FileSystemDirectoryHandle;
      const dirName = handle.name;
      const currentPath = parentPath ? `${parentPath}/${dirName}` : dirName;
      const dirId = rootId ? `${rootId}/${dirName}` : dirName;
      
      const directoryNode: FileNode = {
        id: dirId,
        name: dirName,
        path: currentPath,
        isDirectory: true,
        children: []
      };
      
      // 读取目录内容
      for await (const [name, childHandle] of dirHandle.entries()) {
        if (childHandle.kind === 'directory') {
          const subDirNodes = await this.buildFileTree(childHandle, currentPath, dirId);
          directoryNode.children!.push(...subDirNodes);
        } else if (name.endsWith('.md')) {
          const fileNode: FileNode = {
            id: `${dirId}/${name}`,
            name: name,
            path: `${currentPath}/${name}`,
            isDirectory: false,
            isFile: true
          };
          directoryNode.children!.push(fileNode);
        }
      }
      
      // 如果目录有子节点（文件或文件夹），则添加到树中
      if (directoryNode.children!.length > 0) {
        fileTree.push(directoryNode);
      }
    }
    
    return fileTree;
  }

  // 读取Markdown文件内容
  static async readMarkdownFile(fileHandle: FileSystemFileHandle): Promise<string> {
    try {
      const file = await fileHandle.getFile();
      return await file.text();
    } catch (error) {
      console.error('读取文件出错:', error);
      return '';
    }
  }

  // 通过路径查找文件句柄
  static async findFileHandleByPath(
    rootHandle: FileSystemDirectoryHandle,
    filePath: string
  ): Promise<FileSystemFileHandle | null> {
    const pathParts = filePath.split('/').filter(part => part);
    let currentHandle: FileSystemHandle = rootHandle;
    
    try {
      for (let i = 0; i < pathParts.length; i++) {
        const part = pathParts[i];
        if (!part) continue;
        
        if (i === pathParts.length - 1 && part.endsWith('.md')) {
          // 最后一部分是文件
          return (currentHandle as FileSystemDirectoryHandle).getFileHandle(part);
        } else {
          // 中间部分是目录
          currentHandle = await (currentHandle as FileSystemDirectoryHandle).getDirectoryHandle(part);
        }
      }
      return null;
    } catch (error) {
      console.error('查找文件句柄出错:', error);
      return null;
    }
  }

  // 保存设置到本地存储
  static saveSettings(settings: { markdownFolderPath: string; lastOpenedFile?: string }): void {
    try {
      localStorage.setItem('markdownManagerSettings', JSON.stringify(settings));
    } catch (error) {
      console.error('保存设置出错:', error);
    }
  }

  // 从本地存储加载设置
  static loadSettings(): { markdownFolderPath: string; lastOpenedFile?: string } {
    try {
      const settingsStr = localStorage.getItem('markdownManagerSettings');
      if (settingsStr) {
        return JSON.parse(settingsStr);
      }
    } catch (error) {
      console.error('加载设置出错:', error);
    }
    return { markdownFolderPath: '' };
  }
}